package com.zdsoft.blp.gongyong.net;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.Map;

/**
 * Created by Administrator on 2016/8/29.
 */
public class WebUtil {
    public static String getResult(Net net){
        SoapObject soapObject=new SoapObject(net.nameSpace,net.methodName);
        //添加参数
        Map<String,Object> map=net.parms;
        if(map!=null && !map.isEmpty()){
            for (String key:map.keySet()){
                soapObject.addProperty(key,map.get(key));
            }
        }
        //类似把这些参数写到服务器
        SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER10);
        envelope.bodyOut=soapObject;//相当于 post请求中的 write
        //是否可以支持.NET//写项目的时候 是false
        envelope.dotNet=false;
        HttpTransportSE httpTransportSE=new HttpTransportSE(net.url);
        //可以调试
        httpTransportSE.debug=true;
        String result="";
        try {
            //真正的去联网，请求服务器
            httpTransportSE.call(null,envelope);
            //获取服务器返回的信息
            SoapObject data= (SoapObject) envelope.bodyIn;
            result=data.getProperty(0).toString();
            Log.e("RESULT:",result);
        } catch (Exception e) {
            Log.e("Exception:",e.toString());
        }
        return result;
    }

    /**
     * 网络是否可用
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {

        ConnectivityManager mgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] info = mgr.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {

                    return true;
                }
            }
        }
        return false;
    }
}
